<template>
  <div class="container">
    <el-row class="section">
      <el-col :span="24" class="section-toolbar">
        <el-select v-model="queryList.dateType" size="small" class="w-120" @change="changeTime">
          <el-option
            v-for="(key,item) in dateTypeOpt"
            :key="key"
            :label="item"
            :value="key"/>
        </el-select>
        <el-date-picker
          v-model="dateRange"
          :clearable="false"
          :picker-options="datePickerOpt"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          class="w-240"
          @change="dateChange"/>
        <el-select v-model="queryList.platform" size="small" class="w-120" >
          <el-option v-for="(key,item) in platformOpt" :key="key" :label="item" :value="key"/>
        </el-select>
        <!-- 版本 -->
        <el-select v-model="queryList.appVersion" size="small" class="w-120" >
          <el-option label="全部版本" value=""/>
          <el-option v-for="item in appVersionOpt" :key="item" :label="item" :value="item"/>
        </el-select>
        <el-select v-model="queryList.lang" size="small" class="w-120" >
          <el-option v-for="(key,item) in langOpt" :key="key" :label="item" :value="key"/>
        </el-select>
        <el-select v-model="queryList.userSelectType" size="small" class="w-120" >
          <el-option v-for="(key,item) in userSelectTypeOpt" :key="key" :label="item" :value="key"/>
        </el-select>
        <el-select v-model="queryList.keepOrLeave" size="small" class="w-100" >
          <el-option v-for="(key,item) in keepOrLeaveOpt" :key="item" :label="item" :value="key"/>
        </el-select>
        <!-- <el-select v-model="queryList.analyzeModel" size="small" class="w-100" >
                    <el-option v-for="(key,item) in analyzeModelOpt" :key="key" :label="item" :value="key"></el-option>
                </el-select> -->
        <el-button type="primary" size="small" icon="el-icon-search" @click="search">搜索</el-button>
      </el-col>
    </el-row>
    <el-card class="section-card">
      <div slot="header">
        <!-- {{title.analyzeModel}} -->
        <span class="echart-title">{{ title.userSelectType }}({{ title.keepOrLeave }})分析</span>
        <div class="section-card-toolbar">
          <el-button v-if="tableData.length>0" size="mini" plain @click="export2Excel">导出</el-button>
        </div>
      </div>
      <el-table v-loading="loading" :data="tableData" :cell-style="cellStyle" border style="width: 100%;margin-top:15px;" size="mini">
        <el-table-column v-for="(item,index) in tableColumn" :key="item" :prop="item" :label="item" align="center" min-width="180" >
          <template slot-scope="scope">
            <span v-if="index==0">{{ scope.row[item] }}</span>
            <span v-else-if="index==1">{{ scope.row[item].count }} 人</span>
            <span v-if="index>1 && scope.row[item]">{{ scope.row[item].countAndRate }} </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
import { getAppVersion, getUserRetention } from '@/api/user-retention.js';
import { userRetentionOpts } from './mixins.js';
import timeUtils from '@/utils/timeHandle.js';
import textFormatting from '@/utils/textFormatting.js';
import '@/assets/css/common/style.scss';
const { exportJsonToExcel, formatJson } = require('@/utils/excel/Export2Excel');
export default {
  mixins: [userRetentionOpts],
  data() {
    return {
      queryList: {
        startTime: `${timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 13,
          'date'
        )}`,
        endTime: `${timeUtils.timeHandle(new Date().getTime(), 'date')}`,
        dateType: 1,
        userSelectType: 3,
        keepOrLeave: 1,
        //   analyzeModel: "30day",
        lang: -1,
        platform: -1,
        appVersion: ''
      },
      title: {
        userSelectType: '活跃用户',
        keepOrLeave: '留存'
        //  analyzeModel: "30日"
      },
      appVersionOpt: [],

      dateRange: [
        timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 13,
          'date'
        ),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ], // 时间默认前两周
      loading: false,
      tableColumn: [],
      tableData: []
    };
  },
  created() {
    this.init();
  },
  methods: {
    changeTime(dateType) {
      let one = 0;
      if (dateType == 1) {
        one = 30 * 24 * 3600 * 1000; // 31天
        this.$nextTick(() => {
          this.datePickerOpt.shortcuts = [
            {
              text: '本周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                const days =
                  new Date().getDay() == 1 ? 0 : new Date().getDay() - 1;
                start.setTime(start.getTime() - 3600 * 1000 * 24 * days);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '本月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setDate(1); // 本月1日
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近7天',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近15天',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 14);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近30天',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 29);
                picker.$emit('pick', [start, end]);
              }
            }
          ];
        });
      } else if (dateType == 2) {
        one = 83 * 24 * 3600 * 1000; // 7周
        this.$nextTick(() => {
          this.datePickerOpt.shortcuts = [
            {
              text: '最近6周', // 前5周+本周
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                const days = new Date().getDay() - 1 + 35;
                start.setTime(start.getTime() - 3600 * 1000 * 24 * days);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近12周', // 十一周+本周
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                const days = new Date().getDay() - 1 + 77;
                start.setTime(start.getTime() - 3600 * 1000 * 24 * days);
                picker.$emit('pick', [start, end]);
              }
            }
          ];
        });
      } else {
        one = 366 * 24 * 3600 * 1000; // 12个月
        this.$nextTick(() => {
          this.datePickerOpt.shortcuts = [
            {
              text: '最近6月', // 5个月+本月
              onClick(picker) {
                const end = new Date();
                const start = new Date(
                  new Date().getFullYear(),
                  new Date().getMonth() - 5,
                  1
                );
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近12月', // 11个月+本月
              onClick(picker) {
                const end = new Date();
                const start = new Date(
                  new Date().getFullYear(),
                  new Date().getMonth() - 11,
                  1
                );
                picker.$emit('pick', [start, end]);
              }
            }
          ];
        });
      }
      this.datePickerOpt.disabledDate = time => {
        if (this.pickerMinDate !== '') {
          const minTime = this.pickerMinDate - one;
          let maxTime = this.pickerMinDate + one;
          if (maxTime > new Date()) {
            maxTime = new Date();
          }
          return time.getTime() < minTime || time.getTime() > maxTime;
        }
        return time.getTime() > Date.now();
      };
    },
    init() {
      this.getAppVersionList();
      this.getUserRetentionList();
    },
    getAppVersionList() {
      getAppVersion()
        .then(result => {
          if (result.code == 200) {
            this.appVersionOpt = result.data;
          } else {
            this.$message.error(result.msg);
          }
        })
        .catch(() => {});
    },
    getUserRetentionList() {
      this.loading = true;
      getUserRetention(this.queryList)
        .then(result => {
          if (result.code == 200) {
            this.loading = false;
            this.tableData = result.data.map(item => {
              item['日期'] = item.timeStr;
              item.data.forEach(dataItem => {
                if (dataItem.name == '原始数据') {
                  let timeName = '';
                  switch (this.queryList.dateType) {
                    case 1:
                      timeName = '当天';
                      break;
                    case 2:
                      timeName = '本周';
                      break;
                    case 3:
                      timeName = '本月';
                      break;
                  }
                  item[timeName] = {
                    count: dataItem.count,
                    rate: dataItem.rate * 100
                  };
                } else {
                  item[dataItem.name] = {
                    countAndRate: `${
                      dataItem.count
                    } 人  /  ${textFormatting.fomatFloat(dataItem.rate * 100, 2)}%`,
                    count: dataItem.count,
                    rate: dataItem.rate
                  };
                }
              });
              delete item.data;
              delete item.timeStr;
              return item;
            });
            this.tableColumn = Object.keys(this.tableData[0]);
          } else {
            this.loading = false;
            this.$message.error(result.msg);
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    dateChange(date) {
      if (date === null) {
        this.queryList.startTime = '';
        this.queryList.endTime = '';
      } else {
        this.queryList.startTime = `${timeUtils.timeHandle(date[0], 'date')}`;
        this.queryList.endTime = `${timeUtils.timeHandle(date[1], 'date')}`;
      }
    },
    findKey(value, obj) {
      return Object.keys(obj)
        .filter(k => obj[k] == value)
        .join();
    },
    search() {
      this.title.keepOrLeave = this.findKey(
        this.queryList.keepOrLeave,
        this.keepOrLeaveOpt
      );
      this.title.userSelectType = this.findKey(
        this.queryList.userSelectType,
        this.userSelectTypeOpt
      );
      this.getUserRetentionList();
    },
    // 导出表格
    export2Excel() {
      // 表头对应字段名，要和下面数据key对应
      const tHeader = [];
      this.tableColumn.forEach((item, index) => {
        tHeader.push(item);
        if (index > 1) tHeader.push(`${item}占比`);
      });
      const importTableData = JSON.parse(JSON.stringify(this.tableData)).map(
        item => {
          Object.keys(item).forEach((itemkey, index) => {
            if (index > 0) {
              item[`${itemkey}占比`] =
                textFormatting.fomatFloat(item[itemkey].rate * 100, 2) + '%';
              item[itemkey] = item[itemkey].count;
            }
          });
          return item;
        }
      );
      // 数据来源
      const data = formatJson(tHeader, importTableData); // 数据格式化
      const newDay = timeUtils.timeHandle(new Date().getTime(), 'date');
      const fileName = `${this.title.userSelectType}(${
        this.title.keepOrLeave
      })分析${newDay}`; // 导出时文件名${this.title.analyzeModel}
      exportJsonToExcel(tHeader, data, fileName); // 导出文件
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (row[column.property] == '' || row[column.property] == undefined) {
        return 'border-bottom: none;border-right: none';
      } else {
        return columnIndex == 0 ? '' : 'background:#ecf5ff;';
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  h3 {
    padding: 0;
    margin: 0;
    display: inline;
  }
  & /deep/ .el-range-editor--small .el-range-separator {
    width: 18px;
  }
  & /deep/ .el-table--border {
    border-bottom: none;
    border-right: none;
  }

  & /deep/ .el-table--medium th {
    padding: 5px 0;
    border-top: 1px solid #dfe6ec;
  }
  & /deep/ .el-table--medium td {
    padding: 0px;
  }
  & /deep/ .el-table--group::after,
  .el-table--border::after,
  .el-table::before {
    height: 0px;
  }
}
.w {
  &-240 {
    width: 240px;
  }
  &-120 {
    width: 120px;
  }
  &-100 {
    width: 100px;
  }
}
.m {
  &b-20 {
    margin-bottom: 20px;
  }
}
.title-center {
  text-align: center;
  padding: 10px 0px 15px;
}
</style>

